#!/bin/bash
# Git 安装脚本
# 功能：安装 Git，配置用户信息，生成 SSH 密钥

set -e

echo "=========================================="
echo "Git 安装开始"
echo "=========================================="

# 检查是否为 root 用户
if [ "$EUID" -ne 0 ]; then 
    echo "请使用 root 用户运行此脚本"
    exit 1
fi

# 1. 检查并配置 yum 镜像源（如果需要）
echo "[1/6] 检查 yum 镜像源配置..."
if ! yum repolist enabled 2>/dev/null | grep -q "mirrors.aliyun.com\|mirrors.tuna.tsinghua.edu.cn\|mirrors.ustc.edu.cn"; then
    echo "检测到未配置国内镜像源，正在配置阿里云镜像源..."
    if [ ! -f /etc/yum.repos.d/CentOS-Base.repo.backup ]; then
        # 备份原有源
        cp /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup 2>/dev/null || true
        
        # 使用阿里云镜像源
        cat > /etc/yum.repos.d/CentOS-Base.repo <<'EOF'
[base]
name=CentOS-$releasever - Base - mirrors.aliyun.com
failovermethod=priority
baseurl=http://mirrors.aliyun.com/centos/$releasever/os/$basearch/
gpgcheck=1
gpgkey=http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7

[updates]
name=CentOS-$releasever - Updates - mirrors.aliyun.com
failovermethod=priority
baseurl=http://mirrors.aliyun.com/centos/$releasever/updates/$basearch/
gpgcheck=1
gpgkey=http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7

[extras]
name=CentOS-$releasever - Extras - mirrors.aliyun.com
failovermethod=priority
baseurl=http://mirrors.aliyun.com/centos/$releasever/extras/$basearch/
gpgcheck=1
gpgkey=http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7
EOF
        echo "✓ 已配置阿里云 yum 镜像源"
    else
        echo "✓ 检测到备份文件，恢复阿里云镜像源配置..."
        if [ -f /etc/yum.repos.d/CentOS-Base.repo.backup ]; then
            cat > /etc/yum.repos.d/CentOS-Base.repo <<'EOF'
[base]
name=CentOS-$releasever - Base - mirrors.aliyun.com
failovermethod=priority
baseurl=http://mirrors.aliyun.com/centos/$releasever/os/$basearch/
gpgcheck=1
gpgkey=http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7

[updates]
name=CentOS-$releasever - Updates - mirrors.aliyun.com
failovermethod=priority
baseurl=http://mirrors.aliyun.com/centos/$releasever/updates/$basearch/
gpgcheck=1
gpgkey=http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7

[extras]
name=CentOS-$releasever - Extras - mirrors.aliyun.com
failovermethod=priority
baseurl=http://mirrors.aliyun.com/centos/$releasever/extras/$basearch/
gpgcheck=1
gpgkey=http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7
EOF
        fi
    fi
    
    # 清理并更新 yum 缓存
    echo "清理并更新 yum 缓存..."
    yum clean all > /dev/null 2>&1 || true
    yum makecache fast > /dev/null 2>&1 || echo "⚠ yum 缓存更新失败，但将继续尝试安装"
else
    echo "✓ 已配置国内镜像源"
fi

# 2. 检查并安装 Git
echo ""
echo "[2/6] 检查并安装 Git..."
if command -v git &> /dev/null; then
    GIT_VERSION=$(git --version | awk '{print $3}')
    echo "✓ Git 已安装，版本: $GIT_VERSION"
    read -p "是否重新安装 Git? (y/N): " REINSTALL
    if [[ ! "$REINSTALL" =~ ^[Yy]$ ]]; then
        echo "跳过 Git 安装"
    else
        echo "重新安装 Git..."
        if yum install -y git; then
            GIT_VERSION=$(git --version | awk '{print $3}')
            echo "✓ Git 安装完成，版本: $GIT_VERSION"
        else
            echo "✗ Git 安装失败，请检查网络连接和镜像源配置"
            exit 1
        fi
    fi
else
    echo "安装 Git..."
    if yum install -y git; then
        GIT_VERSION=$(git --version | awk '{print $3}')
        echo "✓ Git 安装完成，版本: $GIT_VERSION"
    else
        echo "✗ Git 安装失败，请检查网络连接和镜像源配置"
        echo "提示：如果仍然失败，请先运行 scripts/k8s/setup-centos.sh 配置镜像源"
        exit 1
    fi
fi

# 3. 配置 Git 用户信息
echo ""
echo "[3/6] 配置 Git 用户信息..."

# 获取当前用户名（如果不是 root）
if [ -n "$SUDO_USER" ]; then
    TARGET_USER="$SUDO_USER"
elif [ "$USER" != "root" ]; then
    TARGET_USER="$USER"
else
    # 如果是 root 用户，需要指定一个普通用户
    echo "检测到 root 用户，需要为普通用户配置 Git"
    read -p "请输入要配置 Git 的用户名（留空则跳过用户信息配置）: " TARGET_USER
fi

if [ -n "$TARGET_USER" ]; then
    # 切换到目标用户的主目录
    TARGET_HOME=$(eval echo ~$TARGET_USER)
    
    # 获取或设置 Git 用户名
    if [ -n "$GIT_USER_NAME" ]; then
        GIT_NAME="$GIT_USER_NAME"
        echo "使用环境变量 GIT_USER_NAME: $GIT_NAME"
    else
        CURRENT_NAME=$(sudo -u $TARGET_USER git config --global user.name 2>/dev/null || echo "")
        if [ -n "$CURRENT_NAME" ]; then
            echo "当前 Git 用户名: $CURRENT_NAME"
            read -p "是否使用当前用户名? (Y/n): " USE_CURRENT
            if [[ "$USE_CURRENT" =~ ^[Nn]$ ]]; then
                read -p "请输入 Git 用户名: " GIT_NAME
            else
                GIT_NAME="$CURRENT_NAME"
            fi
        else
            read -p "请输入 Git 用户名: " GIT_NAME
        fi
    fi
    
    # 获取或设置 Git 邮箱
    if [ -n "$GIT_USER_EMAIL" ]; then
        GIT_EMAIL="$GIT_USER_EMAIL"
        echo "使用环境变量 GIT_USER_EMAIL: $GIT_EMAIL"
    else
        CURRENT_EMAIL=$(sudo -u $TARGET_USER git config --global user.email 2>/dev/null || echo "")
        if [ -n "$CURRENT_EMAIL" ]; then
            echo "当前 Git 邮箱: $CURRENT_EMAIL"
            read -p "是否使用当前邮箱? (Y/n): " USE_CURRENT
            if [[ "$USE_CURRENT" =~ ^[Nn]$ ]]; then
                read -p "请输入 Git 邮箱: " GIT_EMAIL
            else
                GIT_EMAIL="$CURRENT_EMAIL"
            fi
        else
            read -p "请输入 Git 邮箱: " GIT_EMAIL
        fi
    fi
    
    # 配置 Git 用户信息
    if [ -n "$GIT_NAME" ] && [ -n "$GIT_EMAIL" ]; then
        sudo -u $TARGET_USER git config --global user.name "$GIT_NAME"
        sudo -u $TARGET_USER git config --global user.email "$GIT_EMAIL"
        echo "✓ Git 用户信息配置完成:"
        echo "  用户名: $GIT_NAME"
        echo "  邮箱: $GIT_EMAIL"
    else
        echo "⚠ 跳过 Git 用户信息配置（用户名或邮箱为空）"
    fi
else
    echo "⚠ 跳过 Git 用户信息配置（未指定用户）"
fi

# 4. 生成 SSH 密钥
echo ""
echo "[4/6] 生成 SSH 密钥..."

if [ -n "$TARGET_USER" ]; then
    SSH_DIR="$TARGET_HOME/.ssh"
    SSH_KEY_TYPE="ed25519"
    SSH_KEY_PATH="$SSH_DIR/id_$SSH_KEY_TYPE"
    
    # 创建 .ssh 目录
    if [ ! -d "$SSH_DIR" ]; then
        mkdir -p "$SSH_DIR"
        chown $TARGET_USER:$TARGET_USER "$SSH_DIR"
        chmod 700 "$SSH_DIR"
        echo "✓ 创建 .ssh 目录: $SSH_DIR"
    fi
    
    # 检查是否已存在 SSH 密钥
    if [ -f "$SSH_KEY_PATH" ] || [ -f "$SSH_DIR/id_rsa" ]; then
        echo "检测到已存在的 SSH 密钥"
        if [ -f "$SSH_KEY_PATH" ]; then
            EXISTING_KEY="$SSH_KEY_PATH"
        else
            EXISTING_KEY="$SSH_DIR/id_rsa"
        fi
        echo "现有密钥: $EXISTING_KEY"
        read -p "是否生成新的 SSH 密钥? (y/N): " GENERATE_NEW
        if [[ ! "$GENERATE_NEW" =~ ^[Yy]$ ]]; then
            echo "使用现有 SSH 密钥"
            SSH_KEY_PATH="$EXISTING_KEY"
        else
            # 备份现有密钥
            BACKUP_KEY="${EXISTING_KEY}.backup.$(date +%Y%m%d_%H%M%S)"
            cp "$EXISTING_KEY" "$BACKUP_KEY" 2>/dev/null || true
            if [ -f "${EXISTING_KEY}.pub" ]; then
                cp "${EXISTING_KEY}.pub" "${BACKUP_KEY}.pub" 2>/dev/null || true
            fi
            echo "✓ 已备份现有密钥到: $BACKUP_KEY"
            
            # 生成新密钥
            if [ "$SSH_KEY_TYPE" = "ed25519" ]; then
                sudo -u $TARGET_USER ssh-keygen -t ed25519 -C "$GIT_EMAIL" -f "$SSH_KEY_PATH" -N ""
            else
                sudo -u $TARGET_USER ssh-keygen -t rsa -b 4096 -C "$GIT_EMAIL" -f "$SSH_KEY_PATH" -N ""
            fi
            chown $TARGET_USER:$TARGET_USER "$SSH_KEY_PATH"*
            chmod 600 "$SSH_KEY_PATH"
            chmod 644 "${SSH_KEY_PATH}.pub"
            echo "✓ SSH 密钥生成完成: $SSH_KEY_PATH"
        fi
    else
        # 生成新密钥
        if [ "$SSH_KEY_TYPE" = "ed25519" ]; then
            sudo -u $TARGET_USER ssh-keygen -t ed25519 -C "$GIT_EMAIL" -f "$SSH_KEY_PATH" -N ""
        else
            sudo -u $TARGET_USER ssh-keygen -t rsa -b 4096 -C "$GIT_EMAIL" -f "$SSH_KEY_PATH" -N ""
        fi
        chown $TARGET_USER:$TARGET_USER "$SSH_KEY_PATH"*
        chmod 600 "$SSH_KEY_PATH"
        chmod 644 "${SSH_KEY_PATH}.pub"
        echo "✓ SSH 密钥生成完成: $SSH_KEY_PATH"
    fi
    
    # 5. 显示 SSH 公钥
    echo ""
    echo "[5/6] SSH 公钥内容:"
    echo "=========================================="
    if [ -f "${SSH_KEY_PATH}.pub" ]; then
        cat "${SSH_KEY_PATH}.pub"
    elif [ -f "$SSH_DIR/id_rsa.pub" ]; then
        cat "$SSH_DIR/id_rsa.pub"
    else
        echo "未找到 SSH 公钥文件"
    fi
    echo "=========================================="
    
    # 6. 配置 SSH 密钥权限
    echo ""
    echo "[6/6] 配置 SSH 密钥权限..."
    chown -R $TARGET_USER:$TARGET_USER "$SSH_DIR"
    chmod 700 "$SSH_DIR"
    find "$SSH_DIR" -type f -name "id_*" ! -name "*.pub" -exec chmod 600 {} \;
    find "$SSH_DIR" -type f -name "*.pub" -exec chmod 644 {} \;
    echo "✓ SSH 密钥权限配置完成"
else
    echo "⚠ 跳过 SSH 密钥生成（未指定用户）"
fi

# 验证 Git 安装
echo ""
echo "=========================================="
echo "验证 Git 安装..."
echo "=========================================="
git --version

if [ -n "$TARGET_USER" ]; then
    echo ""
    echo "Git 配置信息:"
    sudo -u $TARGET_USER git config --global --list | grep -E "user.name|user.email" || echo "未配置用户信息"
fi

echo ""
echo "=========================================="
echo "Git 安装完成！"
echo "=========================================="
echo ""
if [ -n "$TARGET_USER" ] && [ -f "${SSH_KEY_PATH}.pub" ]; then
    echo "下一步："
    echo "1. 复制上面的 SSH 公钥内容"
    echo "2. 登录到您的 Git 仓库（Gitee/GitHub 等）"
    echo "3. 进入 设置 -> SSH 公钥"
    echo "4. 粘贴公钥并保存"
    echo ""
    echo "测试 SSH 连接（以 Gitee 为例）:"
    echo "  ssh -T git@gitee.com"
fi

